package com.edu.web.controller;

import com.alibaba.fastjson.JSON;
import com.edu.model.Response;
import com.edu.model.dto.EventDefineDto;
import com.edu.service.EventDefineService;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.Charset;

@RestController
public class CompilerController {

    @Resource
    private EventDefineService eventDefineService;

    @PostMapping("compile")
    public Object compile(@RequestBody EventDefineDto eventDefineDto) {
        Response response = eventDefineService.saveEventDefine(eventDefineDto);
        return response;
    }

    @PostMapping("testCompile")
    public Object testCompile(String filename) {
        ClassPathResource classPathResource = new ClassPathResource("sample/" + filename);
        String json = null;
        try {
            json = IOUtils.toString(classPathResource.getInputStream(), Charset.forName("UTF-8"));
        } catch (IOException e) {
            return Response.fail(filename + " toString error: " + e.getMessage());
        }
        EventDefineDto eventDefineDto = JSON.parseObject(json, EventDefineDto.class);
        Response response = eventDefineService.saveEventDefine(eventDefineDto);
        return response;
    }

}
